/* 用户的增删改查 */
const router = require("koa-router")(),
  tools = require("../../module/tools"),
  DB = require("../../module/db.js"),
  svgCaptcha = require("svg-captcha");

router.get("/", async ctx => {
  await ctx.render("admin/login");
});
router.post("/doLogin", async ctx => {
  console.log(ctx.request.body);
  //先去数据库匹配
  let username = ctx.request.body.username;
  let password = ctx.request.body.password;
  let code = ctx.request.body.code;
  console.log(tools.md5(password));
  /*  await DB.insert('admin',{
    username:"admin",
    password:tools.md5(password),
    last_time:new Date()
  }) */
  // 1验证密码是否合法
  // 2去数据库匹配
  // 3成功写入seisson

  if (code.toLocaleLowerCase() == ctx.session.code.toLocaleLowerCase()) {
    //后台验证用户名密码是否合法

    var result = await DB.find("admin", {
      username: username,
      password: tools.md5(password)
    });
    console.log(result)
    if (result.length > 0) {
      console.log("成功");
      ctx.session.userInfo = result[0];
      console.log(result[0]._id);
      
      await DB.update(
        "admin",
        { _id: DB.getObjectId(result[0]._id)},
        {
          last_time: new Date()
        }
      );

      ctx.redirect(ctx.state.__HOST__ + "/admin");
    } else {
      console.log("失败");
      ctx.render("admin/error", {
        message: "用户名或密码错误",
        redirect: ctx.state.__HOST__ + "/admin/login"
      });
    }
  } else {
    ctx.render("admin/error", {
      message: "验证码失败",
      redirect: ctx.state.__HOST__ + "/admin/login"
    });
    console.log("验证码失败");
  }

  /* 验证码 */

  // let result = await DB.insert("admin", {
  //   username: "admin",
  //   password:tools.md5(password)
  // });
  // console.log(result);
  // 验证是否合法
  //去数据库匹配
  // password
  // let data = await DB.update('user',{'username':'赵柳'},{'username':'李四111'})
  //   console.log(data);
});
router.get("/code", async ctx => {
  var captcha = svgCaptcha.create({
    size: 4,
    fontSize: 50,
    width: 120,
    height: 35,
    background: "#cc9966"
  });

  /*  加法  
   var captcha = svgCaptcha.createMathExpr({
    size:6,
    fontSize:50,
    width:100,
    height:40,
    background:"#cc9966"
  }); */
  console.log(captcha.text);
  //保存生成的验证码
  ctx.session.code = captcha.text;

  //设置响应头
  ctx.response.type = "image/svg+xml";
  ctx.body = captcha.data;
});
router.get("/loginOut", async ctx => {
  ctx.session.userInfo = null;
  ctx.redirect(ctx.state.__HOST__ + "/admin/login");
});

module.exports = router.routes();
